package com.etonenet.service.system.security;

import java.util.ArrayList;
import java.util.List;

import javax.annotation.Resource;

import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import com.etonenet.entity.system.security.RoleUser;
import com.etonenet.entity.system.security.UserBs;
import com.etonenet.repository.system.security.RoleUserRepository;
import com.etonenet.repository.system.security.UserBsRepository;

@Service
public class UserDetailsService implements org.springframework.security.core.userdetails.UserDetailsService {

	@Resource
	private UserBsRepository userBsEm;

	@Resource
	private RoleUserRepository roleUserEm;

	@Override
	public UserDetails loadUserByUsername(String loginName) throws UsernameNotFoundException {

		UserBs u = userBsEm.findByLoginName(loginName);
		if (u == null)
			throw new UsernameNotFoundException("用户名密码错误");

		List<GrantedAuthority> auths = new ArrayList<GrantedAuthority>();
		auths.add(new SimpleGrantedAuthority("ROLE_USER"));

		for (RoleUser ru : roleUserEm.findByUserId(u.getUserId())) {
			auths.add(new SimpleGrantedAuthority(ru.getRole().getRoleName()));
		}

		boolean enabled = u.getUserState() == 1;
		// boolean accountNonExpired = u.getAccountExpire() == 1;
		// boolean accountNonLocked = u.getAccountLock() == 1;

		return new CustomUser(u, u.getLoginName(), u.getPassword(), enabled, true, true, true, auths);
	}

}
